package com.ykq.aspect;

import com.alibaba.fastjson.JSON;
import com.ykq.annotation.MethodAnnotation;
import com.ykq.dao.OperLogMapper;
import com.ykq.entity.EmpInfo;
import com.ykq.entity.OperLog;
import com.ykq.vo.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private OperLogMapper operLogMapper;
    @Pointcut("@annotation(com.ykq.annotation.MethodAnnotation)")
    private void pointcut(){}

    @Autowired
    private HttpServletRequest request;
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        //1.创建一个OperLog对象---
        OperLog operLog = new OperLog();
        //设置操作的方法名
        operLog.setMethod(joinPoint.getSignature().getName());
        //设置请求方式
        operLog.setRequestmethod(request.getMethod());
        //设置操作人的名称
        HttpSession session = request.getSession();
        EmpInfo empInfo= (EmpInfo) session.getAttribute("empinfo");
        operLog.setOpername(empInfo.getEname());
        //设置请求的路径
        operLog.setOperurl(request.getRequestURI());
        //设置请求的ip
        operLog.setOperip(request.getRemoteAddr());
        //设置操作日期
        operLog.setOpertime(new Date());
        //1.获取方法上的注解对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        MethodAnnotation methodAnnotation = method.getAnnotation(MethodAnnotation.class);
        String value = methodAnnotation.value();
        operLog.setBusinesstype(value);
        //设置请求的参数
        Object[] args = joinPoint.getArgs();
        operLog.setOperparam(Arrays.asList(args).toString());
        try {
            //执行业务功能
            Object result = joinPoint.proceed();
            operLog.setJsonresult(JSON.toJSONString(result));
            operLog.setStatus(0);
            return result;
        } catch (Throwable e) {
            operLog.setStatus(1);
//            throw new RuntimeException(e);
        } finally {
            operLogMapper.insert(operLog);
        }
        return new R(5000,"操作失败",null);
    }
}













